package com.hujiang.basic.search.common.converter.resp;

import com.hujiang.basic.search.common.converter.Converter;
import com.hujiang.basic.search.model.HJSuggestResponse;
import org.elasticsearch.action.suggest.SuggestResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by zhanglibin on 2017/3/30.
 */
@Component
public class SuggestHitsConverter implements Converter<SuggestResponse, HJSuggestResponse> {
    @Override
    public HJSuggestResponse convert(SuggestResponse in) {
        if (null == in || in.getSuggest().size() == 0) {
            return null;
        }
        HJSuggestResponse suggestResponse = new HJSuggestResponse();
        List<String> hits = new ArrayList<>();
        Iterator iter = in.getSuggest().iterator();
        while (iter.hasNext()) {
            String name = ((Iterator<Suggest.Suggestion<Suggest.Suggestion.Entry<Suggest.Suggestion.Entry.Option>>>) (iter)).next().getName();
            if (in.getSuggest().getSuggestion(name).getEntries().size() > 0) {
                if (in.getSuggest().getSuggestion(name).getEntries().get(0).getOptions().size() > 0) {
                    for (Suggest.Suggestion.Entry.Option option : in.getSuggest().getSuggestion(name).getEntries().get(0).getOptions()) {
                        hits.add(option.getText().toString());
                    }
                }
            }
        }
        suggestResponse.setHits(hits);
        suggestResponse.setStatus(0);
        return suggestResponse;
    }
}
